package main

import (
	"crypto/sha256"
	"fmt"
	"strings"
)

// 计算哈希
func calHash(data []byte) []byte {
	hash := sha256.Sum256(data)
	return hash[:]
}

// MerkleNode Merkle树结构体
type MerkleNode struct {
	hash       []byte
	leftChild  *MerkleNode
	rightChild *MerkleNode
}

// NewMerkleLeaf 创建叶子节点
func NewMerkleLeaf(data []byte) *MerkleNode {
	return &MerkleNode{
		hash: calHash(data),
	}

}

// NewMerkleParent 创建父节点
func NewMerkleParent(left *MerkleNode, right *MerkleNode) *MerkleNode {
	parent := &MerkleNode{
		leftChild:  left,
		rightChild: right,
	}
	parent.hash = calHash(append(left.hash, right.hash...))
	return parent
}

func (node *MerkleNode) PrintHash() {
	fmt.Printf("Hash: %x\n", node.hash)
}
func split(data string) []string {
	return strings.Split(data, " ")
	//return []byte(strings.Split(data,"")[0])
}

// 叶节点
func createLeaf(data1 string) []*MerkleNode {
	data := split(data1)
	var leafs []*MerkleNode
	if len(data)%2 == 1 {
		data = append(data, data[len(data)-1])
	}
	for _, v := range data {
		leafs = append(leafs, NewMerkleLeaf([]byte(v)))
	}
	return leafs
}

// 父节点
func creatLayer(layer []*MerkleNode) []*MerkleNode {
	var root []*MerkleNode
	count := len(layer)
	if count%2 == 0 {
		var i = 0
		for {
			if i <= count/2-1 {
				root = append(root, NewMerkleParent(layer[2*i], layer[2*i+1]))
				i++
			} else {
				break
			}
		}
		return creatLayer(root)
	} else {
		root = layer
		return root
	}
}
func main() {
	data := "hhhh"

	n := creatLayer(createLeaf(data))
	n[0].PrintHash()

	//data1 := createLeaf(data)
	////root := creatLayer(data1)
	////
	//////打印节点的值
	////root.PrintHash()
	//root[0].PrintHash()
}
